package com.mresources.web.service;

import com.mresources.common.dto.bo.UploadFileBo;
import com.mresources.common.dto.vo.UploadFileVO;
import com.mresources.resources.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

@Service
public class ResourcesService {
    @Resource
    private FileService fileService;

    public UploadFileVO handleUploadFile(HttpServletRequest request, UploadFileBo uploadFileDto) {
        if (request instanceof StandardMultipartHttpServletRequest) {

            StandardMultipartHttpServletRequest fileRequest = (StandardMultipartHttpServletRequest) request;
            try {
                Iterator<String> iterator = fileRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile multipartFile = fileRequest.getFile(iterator.next());
                    if (multipartFile != null) {
                        return fileService.writeFile(uploadFileDto, multipartFile.getInputStream());
                    }
                }
            } catch (Exception ignored) {

            }
        }
        return null;
    }
}
